package com.hjw.service.impl;


import com.hjw.dao.CartDao;
import com.hjw.entity.Cart;
import com.hjw.entity.Hot;
import com.hjw.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author hjw
 * @date 2021年10月15日 23:04
 * @description 购物车服务实现类
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartDao cartDao;
    @Autowired
    private RedisTemplate<String, Cart> redisTemplate;

    @Override
    public List<Cart> findAll() {
        return cartDao.findAll();
    }

    @Override
    public Cart findById(Integer id) {
        Cart cart = redisTemplate.opsForValue().get("cart:" + id);
        if (cart != null) {
            return cart;
        }
        cart = cartDao.findById(id);
        if (cart == null) {
            return null;
        }
        redisTemplate.opsForValue().set("cart:" + id, cart,7200, TimeUnit.SECONDS);
        return cart;
    }

    @Override
    public List<Cart> findByUid(Integer uid) {
        return cartDao.findByUid(uid);
    }

    @Override
    public int add(Cart cart) {
        int result = cartDao.add(cart);
        if (result > 0) {
            redisTemplate.opsForValue().set("cart:" + cart.getId(), cart,7200, TimeUnit.SECONDS);
        }
        return result;
    }

    @Override
    public int delete(Integer id) {
        redisTemplate.delete("cart:" + id);
        int delete = cartDao.delete(id);
        redisTemplate.delete("cart:" + id);
        return delete;
    }

    @Override
    public int update(Integer uid, Integer id, Integer num) {
        redisTemplate.delete("cart:" + id);
        int update = cartDao.update(uid, id, num);
        redisTemplate.delete("cart:" + id);
        return update;
    }



}
